package com.ktgj.flight.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ktgj.common.core.enums.EnumHelper;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.Employee;
import com.ktgj.flight.common.linkstar.LinkStar;
import com.ktgj.flight.common.linkstar.domain.baseclass.Source;
import com.ktgj.flight.domain.*;
import com.ktgj.flight.domain.InterfaceEntity.MoCreateOrderRequest;
import com.ktgj.flight.domain.InterfaceEntity.MoPassenger;
import com.ktgj.flight.domain.InterfaceEntity.MoSegment;
import com.ktgj.flight.domain.vo.EmployeeTaskInfo;
import com.ktgj.flight.domain.vo.FlightOrderResponse;
import com.ktgj.flight.service.IFlightOrderInfoService;
import com.ktgj.flight.service.IFlightOrderInfoTicketsService;
import com.ktgj.flight.service.IFlightService;
import net.bytebuddy.agent.builder.AgentBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.flight.mapper.FlightOrderExceptionMapper;
import com.ktgj.flight.service.IFlightOrderExceptionService;

/**
 * 机票订单异常Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-06-21
 */
@Service
public class FlightOrderExceptionServiceImpl implements IFlightOrderExceptionService 
{

    private final Logger logger = LoggerFactory.getLogger(FlightOrderExceptionServiceImpl.class);

    @Autowired
    private FlightOrderExceptionMapper flightOrderExceptionMapper;

    @Autowired
    private IFlightOrderInfoTicketsService flightOrderInfoTicketsService;

    @Autowired
    private IFlightOrderInfoService flightOrderInfoService;

    @Autowired
    private IFlightService flightService;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    /**
     * 查询机票订单异常
     * 
     * @param exceptionId 机票订单异常ID
     * @return 机票订单异常
     */
    @Override
    public FlightOrderException selectFlightOrderExceptionById(Long exceptionId)
    {
        return flightOrderExceptionMapper.selectFlightOrderExceptionById(exceptionId);
    }

    /**
     * 查询机票订单异常列表
     * 
     * @param flightOrderException 机票订单异常
     * @return 机票订单异常
     */
    @Override
    public List<FlightOrderException> selectFlightOrderExceptionList(FlightOrderException flightOrderException)
    {
        return flightOrderExceptionMapper.selectFlightOrderExceptionList(flightOrderException);
    }

    /**
     * 新增机票订单异常
     * 
     * @param flightOrderException 机票订单异常
     * @return 结果
     */
    @Override
    public int insertFlightOrderException(FlightOrderException flightOrderException)
    {
        flightOrderException.setCreateTime(DateUtils.getNowDate());
        return flightOrderExceptionMapper.insertFlightOrderException(flightOrderException);
    }

    /**
     * 修改机票订单异常
     * 
     * @param flightOrderException 机票订单异常
     * @return 结果
     */
    @Override
    public int updateFlightOrderException(FlightOrderException flightOrderException)
    {
        return flightOrderExceptionMapper.updateFlightOrderException(flightOrderException);
    }

    /**
     * 修改机票订单异常
     *
     * @param flightOrderException 机票订单异常
     * @return 结果
     */
    @Override
    public int updateFlightOrderExceptionByOrderId(FlightOrderException flightOrderException) {
        return flightOrderExceptionMapper.updateFlightOrderExceptionByOrderId(flightOrderException);
    }

    /**
     * 批量删除机票订单异常
     * 
     * @param exceptionIds 需要删除的机票订单异常ID
     * @return 结果
     */
    @Override
    public int deleteFlightOrderExceptionByIds(Long[] exceptionIds)
    {
        return flightOrderExceptionMapper.deleteFlightOrderExceptionByIds(exceptionIds);
    }

    /**
     * 删除机票订单异常信息
     * 
     * @param exceptionId 机票订单异常ID
     * @return 结果
     */
    @Override
    public int deleteFlightOrderExceptionById(Long exceptionId)
    {
        return flightOrderExceptionMapper.deleteFlightOrderExceptionById(exceptionId);
    }

    //机票订单异常列表
    @Override
    public List<FlightOrderException> queryFlightOrderExceptionList(String ticketChannel, String ticketWay, String orderType, String orderId) {
        List<FlightOrderException> exceptions = flightOrderExceptionMapper.queryFlightOrderExceptionList(ticketChannel, ticketWay, orderType, orderId);
        return exceptions;
    }

    //出票处理-个人
    @Override
    public FlightOrderExceptionDetails orderExceptionDetails(String orderId) {
        FlightOrderExceptionDetails exceptionDetails = flightOrderExceptionMapper.orderExceptionDetails(orderId);
        List<FlightOrderInfoTickets> infoTicketsList = flightOrderInfoTicketsService.selectFlightOrderInfoTicketsByOrderId(Long.valueOf(orderId));
        if (infoTicketsList.size() > 1) {
            if (infoTicketsList.get(1).getTripType().equals("rt")) {
                exceptionDetails.setFlightinfo(infoTicketsList.get(0).getOrgAirport() + infoTicketsList.get(0).getDstAirport() + " " + infoTicketsList.get(1).getOrgAirport() + infoTicketsList.get(1).getDstAirport());
                exceptionDetails.setFlightno(infoTicketsList.get(0).getFlight() + " " + infoTicketsList.get(1).getFlight());
            } else if (infoTicketsList.get(1).getTripType().equals("ot")) {
                exceptionDetails.setFlightinfo(infoTicketsList.get(0).getOrgAirport() + infoTicketsList.get(1).getDstAirport());
                exceptionDetails.setFlightno(infoTicketsList.get(0).getFlight() + " " + infoTicketsList.get(1).getFlight());
            } else if (infoTicketsList.get(1).getTripType().equals("ow")) {
                exceptionDetails.setFlightinfo(infoTicketsList.get(0).getOrgAirport() + infoTicketsList.get(0).getDstAirport());
                exceptionDetails.setFlightno(infoTicketsList.get(0).getFlight());
            }
        } else {
            exceptionDetails.setFlightinfo(infoTicketsList.get(0).getOrgAirport() + infoTicketsList.get(0).getDstAirport());
            exceptionDetails.setFlightno(infoTicketsList.get(0).getFlight());
        }
        infoTicketsList.forEach(item -> {
            FlightOrderExceptionPassenger passenger = new FlightOrderExceptionPassenger();
            BeanUtils.copyProperties(item, passenger);
            exceptionDetails.getPassengers().add(passenger);
        });
        return exceptionDetails;
    }

    //操作PNR
    @Override
    public int operationPNR(Employee employee, String orderId) {
        MoCreateOrderRequest moRequest = new MoCreateOrderRequest();
        FlightOrderInfo orderInfo = flightOrderInfoService.selectFlightOrderInfoById(Long.valueOf(orderId));
        List<FlightOrderInfoTickets> orderInfoTickets = flightOrderInfoTicketsService.selectFlightOrderInfoTicketsByOrderId(Long.valueOf(orderId));
        if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.LinkStar.toString())) {
            moRequest.channelType = EnumHelper.RequestType.LinkStar.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.HangBanGuanJia.toString())) {
            moRequest.channelType = EnumHelper.RequestType.HangBanGuanJia.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.G5.toString())) {
            moRequest.channelType = EnumHelper.RequestType.G5.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.DR.toString())) {
            moRequest.channelType = EnumHelper.RequestType.DR.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Spring.toString())) {
            moRequest.channelType = EnumHelper.RequestType.Spring.getValue();
        } else if (orderInfo.getTicketWay().equals(EnumHelper.RequestType.Qunar.toString())) {
            moRequest.channelType = EnumHelper.RequestType.Qunar.getValue();
        }
        if (orderInfo.getTripType().equals("ow")) {
            moRequest.TripType = 1;
            MoSegment moSegment = new MoSegment();
            moSegment.Airline = orderInfoTickets.get(0).getAirliner();
            moSegment.ArrDate = orderInfoTickets.get(0).getArrivalTime();
            moSegment.Cabin = orderInfoTickets.get(0).getCabin();
            moSegment.DepDate = orderInfoTickets.get(0).getDepartureTime();
            moSegment.DstAirport = orderInfoTickets.get(0).getDstAirport();
            moSegment.FlightNo = orderInfoTickets.get(0).getFlight();
            moSegment.OilFee = orderInfoTickets.get(0).getFuelFee();
            moSegment.OrgAirport = orderInfoTickets.get(0).getOrgAirport();
            moSegment.PlaneStyle = orderInfoTickets.get(0).getFlightType();
            moSegment.Tax = orderInfoTickets.get(0).getAirportFee();
            moSegment.orgTerminal = orderInfoTickets.get(0).getDepTerm().substring(orderInfoTickets.get(0).getDepTerm().length() - 2);
            moSegment.dstTerminal = orderInfoTickets.get(0).getArrTerm().substring(orderInfoTickets.get(0).getArrTerm().length() - 2);
            moSegment.cabinLevel = orderInfoTickets.get(0).getCabinGrade();
            moSegment.PrintPrice = orderInfoTickets.get(0).getTicketPrice();
            moRequest.ListGoSegment.add(moSegment);
            if (orderInfoTickets.size() > 1) {
                if (orderInfoTickets.get(1).getTripType().equals("ot")) {
                    MoSegment moSegmentGo = new MoSegment();
                    moSegmentGo.Airline = orderInfoTickets.get(1).getAirliner();
                    moSegmentGo.ArrDate = orderInfoTickets.get(1).getArrivalTime();
                    moSegmentGo.Cabin = orderInfoTickets.get(1).getCabin();
                    moSegmentGo.DepDate = orderInfoTickets.get(1).getDepartureTime();
                    moSegmentGo.DstAirport = orderInfoTickets.get(1).getDstAirport();
                    moSegmentGo.FlightNo = orderInfoTickets.get(1).getFlight();
                    moSegmentGo.OilFee = orderInfoTickets.get(1).getFuelFee();
                    moSegmentGo.OrgAirport = orderInfoTickets.get(1).getOrgAirport();
                    moSegmentGo.PlaneStyle = orderInfoTickets.get(1).getFlightType();
                    moSegmentGo.Tax = orderInfoTickets.get(1).getAirportFee();
                    moSegmentGo.orgTerminal = orderInfoTickets.get(1).getDepTerm().substring(orderInfoTickets.get(1).getDepTerm().length() - 2);
                    moSegmentGo.dstTerminal = orderInfoTickets.get(1).getArrTerm().substring(orderInfoTickets.get(1).getArrTerm().length() - 2);
                    moSegmentGo.cabinLevel = orderInfoTickets.get(1).getCabinGrade();
                    moSegmentGo.PrintPrice = orderInfoTickets.get(1).getTicketPrice();
                    moRequest.ListGoSegment.add(moSegmentGo);
                    for (int i = (orderInfoTickets.size() - 1); i >= 0; i--) {
                        if (i%2 == 1) {
                            MoPassenger passenger = new MoPassenger();
                            passenger.AirportTax = orderInfoTickets.get(i).getAirportFee();
                            passenger.Birthday = orderInfoTickets.get(i).getGuestBirthday();
                            passenger.FuelTax = orderInfoTickets.get(i).getFuelFee();
                            passenger.IDNO = orderInfoTickets.get(i).getGuestIdno();
                            passenger.IDType = Math.toIntExact(orderInfoTickets.get(i).getIdTypeId());
                            passenger.PassengerMobile = orderInfoTickets.get(i).getGuestMobile();
                            passenger.PassengerName = orderInfoTickets.get(i).getGuestName();
                            if (orderInfoTickets.get(i).getGuestType().equals("成人"))  {
                                passenger.PassengerType = 1;
                            } else if (orderInfoTickets.get(i).getGuestType().equals("儿童")) {
                                passenger.PassengerType = 2;
                            } else if (orderInfoTickets.get(i).getGuestType().equals("婴儿")) {
                                passenger.PassengerType = 3;
                            }
                            if (orderInfoTickets.get(i).getGuestSex().equals("M")) {
                                passenger.Sex = false;
                            } else if (orderInfoTickets.get(i).getGuestSex().equals("F")) {
                                passenger.Sex = true;
                            }
                            passenger.TicketAmount = orderInfoTickets.get(i).getTicketPrice();
                            moRequest.ListMoPassenger.add(passenger);
                        }
                    }
                } else {
                    for (FlightOrderInfoTickets ticket : orderInfoTickets) {
                        MoPassenger passenger = new MoPassenger();
                        passenger.AirportTax = ticket.getAirportFee();
                        passenger.Birthday = ticket.getGuestBirthday();
                        passenger.FuelTax = ticket.getFuelFee();
                        passenger.IDNO = ticket.getGuestIdno();
                        passenger.IDType = Math.toIntExact(ticket.getIdTypeId());
                        passenger.PassengerMobile = ticket.getGuestMobile();
                        passenger.PassengerName = ticket.getGuestName();
                        if (ticket.getGuestType().equals("成人"))  {
                            passenger.PassengerType = 1;
                        } else if (ticket.getGuestType().equals("儿童")) {
                            passenger.PassengerType = 2;
                        } else if (ticket.getGuestType().equals("婴儿")) {
                            passenger.PassengerType = 3;
                        }
                        if (ticket.getGuestSex().equals("M")) {
                            passenger.Sex = false;
                        } else if (ticket.getGuestSex().equals("F")) {
                            passenger.Sex = true;
                        }
                        passenger.TicketAmount = ticket.getTicketPrice();
                        moRequest.ListMoPassenger.add(passenger);
                    }
                }
            } else {
                MoPassenger passenger = new MoPassenger();
                passenger.AirportTax = orderInfoTickets.get(0).getAirportFee();
                passenger.Birthday = orderInfoTickets.get(0).getGuestBirthday();
                passenger.FuelTax = orderInfoTickets.get(0).getFuelFee();
                passenger.IDNO = orderInfoTickets.get(0).getGuestIdno();
                passenger.IDType = Math.toIntExact(orderInfoTickets.get(0).getIdTypeId());
                passenger.PassengerMobile = orderInfoTickets.get(0).getGuestMobile();
                passenger.PassengerName = orderInfoTickets.get(0).getGuestName();
                if (orderInfoTickets.get(0).getGuestType().equals("成人"))  {
                    passenger.PassengerType = 1;
                } else if (orderInfoTickets.get(0).getGuestType().equals("儿童")) {
                    passenger.PassengerType = 2;
                } else if (orderInfoTickets.get(0).getGuestType().equals("婴儿")) {
                    passenger.PassengerType = 3;
                }
                if (orderInfoTickets.get(0).getGuestSex().equals("M")) {
                    passenger.Sex = false;
                } else if (orderInfoTickets.get(0).getGuestSex().equals("F")) {
                    passenger.Sex = true;
                }
                passenger.TicketAmount = orderInfoTickets.get(0).getTicketPrice();
                moRequest.ListMoPassenger.add(passenger);
            }
        } else if (orderInfo.getTripType().equals("rt")) {
            moRequest.TripType = 2;
            MoSegment moSegment = new MoSegment();
            moSegment.Airline = orderInfoTickets.get(0).getAirliner();
            moSegment.ArrDate = orderInfoTickets.get(0).getArrivalTime();
            moSegment.Cabin = orderInfoTickets.get(0).getCabin();
            moSegment.DepDate = orderInfoTickets.get(0).getDepartureTime();
            moSegment.DstAirport = orderInfoTickets.get(0).getDstAirport();
            moSegment.FlightNo = orderInfoTickets.get(0).getFlight();
            moSegment.OilFee = orderInfoTickets.get(0).getFuelFee();
            moSegment.OrgAirport = orderInfoTickets.get(0).getOrgAirport();
            moSegment.PlaneStyle = orderInfoTickets.get(0).getFlightType();
            moSegment.Tax = orderInfoTickets.get(0).getAirportFee();
            moSegment.orgTerminal = orderInfoTickets.get(0).getDepTerm().substring(orderInfoTickets.get(0).getDepTerm().length() - 2);
            moSegment.dstTerminal = orderInfoTickets.get(0).getArrTerm().substring(orderInfoTickets.get(0).getArrTerm().length() - 2);
            moSegment.cabinLevel = orderInfoTickets.get(0).getCabinGrade();
            moSegment.PrintPrice = orderInfoTickets.get(0).getTicketPrice();
            moRequest.ListGoSegment.add(moSegment);

            MoSegment backSegment = new MoSegment();
            backSegment.Airline = orderInfoTickets.get(1).getAirliner();
            backSegment.ArrDate = orderInfoTickets.get(1).getArrivalTime();
            backSegment.Cabin = orderInfoTickets.get(1).getCabin();
            backSegment.DepDate = orderInfoTickets.get(1).getDepartureTime();
            backSegment.DstAirport = orderInfoTickets.get(1).getDstAirport();
            backSegment.FlightNo = orderInfoTickets.get(1).getFlight();
            backSegment.OilFee = orderInfoTickets.get(1).getFuelFee();
            backSegment.OrgAirport = orderInfoTickets.get(1).getOrgAirport();
            backSegment.PlaneStyle = orderInfoTickets.get(1).getFlightType();
            backSegment.Tax = orderInfoTickets.get(1).getAirportFee();
            backSegment.orgTerminal = orderInfoTickets.get(1).getDepTerm().substring(orderInfoTickets.get(1).getDepTerm().length() - 2);
            backSegment.dstTerminal = orderInfoTickets.get(1).getArrTerm().substring(orderInfoTickets.get(1).getArrTerm().length() - 2);
            backSegment.cabinLevel = orderInfoTickets.get(1).getCabinGrade();
            backSegment.PrintPrice = orderInfoTickets.get(1).getTicketPrice();
            moRequest.ListBackSegment.add(backSegment);
            for (int i = (orderInfoTickets.size() - 1); i >= 0; i--) {
                if (i%2 == 1) {
                    MoPassenger passenger = new MoPassenger();
                    passenger.AirportTax = orderInfoTickets.get(i).getAirportFee();
                    passenger.Birthday = orderInfoTickets.get(i).getGuestBirthday();
                    passenger.FuelTax = orderInfoTickets.get(i).getFuelFee();
                    passenger.IDNO = orderInfoTickets.get(i).getGuestIdno();
                    passenger.IDType = Math.toIntExact(orderInfoTickets.get(i).getIdTypeId());
                    passenger.PassengerMobile = orderInfoTickets.get(i).getGuestMobile();
                    passenger.PassengerName = orderInfoTickets.get(i).getGuestName();
                    if (orderInfoTickets.get(i).getGuestType().equals("成人"))  {
                        passenger.PassengerType = 1;
                    } else if (orderInfoTickets.get(i).getGuestType().equals("儿童")) {
                        passenger.PassengerType = 2;
                    } else if (orderInfoTickets.get(i).getGuestType().equals("婴儿")) {
                        passenger.PassengerType = 3;
                    }
                    if (orderInfoTickets.get(i).getGuestSex().equals("M")) {
                        passenger.Sex = false;
                    } else if (orderInfoTickets.get(i).getGuestSex().equals("F")) {
                        passenger.Sex = true;
                    }
                    passenger.TicketAmount = orderInfoTickets.get(i).getTicketPrice();
                    moRequest.ListMoPassenger.add(passenger);
                }
            }
        }
        FlightOrderResponse response = flightService.createPNR(moRequest);
        if (response.isHasSuccess()) {
            orderInfo.setPnr(response.getOrderId());
            orderInfo.setBigpnr(response.getMsg());
            orderInfo.setTicketAmount(response.getTotalPay());
            int info = flightOrderInfoService.updateFlightOrderInfo(orderInfo);
            FlightOrderException exception = new FlightOrderException();
            exception.setPnr(response.getOrderId());
            exception.setOrderId(orderId);
            exception.setOpreateTime(new Date());
            exception.setOpreator(employee.getEmployeeId());
            int byOrderId = flightOrderExceptionMapper.updateFlightOrderExceptionByOrderId(exception);
            if (info > 0 && byOrderId > 0) {
                return info;
            }
        }
        return 0;
    }

    @Override
    public boolean assignEmployeeTask()
    {
        try
        {
            //获取当前在线的员工
            List<Employee> lstEmp = remoteCustomerService.getOnlineEmployeeList();
            List<EmployeeTaskInfo> lstEmployeeTask = new ArrayList<>();
            //获取今天所有的任务列表
            List<FlightOrderException> lstAssignOrder = flightOrderExceptionMapper.selectFlightOrderExceptionToday().stream().filter(item -> item.getEmployeeId() != null).collect(Collectors.toList());
            for (Employee employee : lstEmp)
            {
                EmployeeTaskInfo employeeTaskInfo = new EmployeeTaskInfo();
                employeeTaskInfo.setEmployeeId(employee.getEmployeeId());
                List<FlightOrderException> lstEmpOrder = lstAssignOrder.stream().filter(item -> item.getEmployeeId().equals(employee.getEmployeeId())).collect(Collectors.toList());
                if (lstEmpOrder.size() == 0)
                {
                    employeeTaskInfo.setTaskCount(0);
                } else
                {
                    employeeTaskInfo.setTaskCount(lstEmpOrder.size());
                }
                employeeTaskInfo.setAssgin(false);
                lstEmployeeTask.add(employeeTaskInfo);
            }
            lstEmployeeTask = lstEmployeeTask.stream().sorted(Comparator.comparing(EmployeeTaskInfo::getTaskCount)).collect(Collectors.toList());
            int taskPos = 1;
            List<FlightOrderException> lstNoAssignOrder = flightOrderExceptionMapper.selectFlightOrderExceptionToday().stream().filter(item -> item.getEmployeeId() == null).collect(Collectors.toList());
            for (FlightOrderException flightOrderException : lstNoAssignOrder)
            {
                for (EmployeeTaskInfo employeeTaskInfo : lstEmployeeTask)
                {
                    if (!employeeTaskInfo.isAssgin())
                    {
                        FlightOrderException updateFlightOrderException = new FlightOrderException();
                        updateFlightOrderException.setEmployeeId(employeeTaskInfo.getEmployeeId());
                        updateFlightOrderException.setExceptionId(flightOrderException.getExceptionId());
                        flightOrderExceptionMapper.updateFlightOrderException(updateFlightOrderException);
                        employeeTaskInfo.setAssgin(true);
                        break;
                    }
                }
                if (taskPos % lstEmployeeTask.size() == 0)
                {
                    lstEmployeeTask.stream().forEach(item -> item.setAssgin(false));
                }
                taskPos++;
            }
            return true;
        } catch (Exception e)
        {
            logger.error(e.getMessage());
            return false;
        }
    }
}
